<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" destroy-on-close @closed="$emit('closed')" :close-on-click-modal="false" :close-on-press-escape="mode != 'show' ? false : true" :width="1000" align-center draggable overflow>
        <el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="110" label-position="right">
            <!-- <el-form-item label="汇款金额" prop="balance_price">
                <el-input v-model="form.balance_price" placeholder="请输入汇款金额" clearable></el-input>
            </el-form-item> -->
            <el-form-item label="汇率" prop="exchange_rate">
                <!-- <el-input v-model="form.exchange_rate" placeholder="请输入汇率" clearable></el-input> -->
                <el-input-number v-model="form.exchange_rate" :min="0" :controls="false" @focus="common.inputFocus($event)" style="width: 100%" @input="calcTotal" />
            </el-form-item>
            <el-form-item label="中间商" prop="middleman_id">
                <el-select v-model="form.middleman_id" placeholder="请选择" filterable clearable>
                    <el-option v-for="item in middleList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="国外扣款账户" prop="from_account">
                <template #label>
                    <div>
                        <div style="font-size: 14px">国外扣款账户</div>
                        <div style="font-size: 14px">扣款总额: {{common.formatNumber(form_amount, 0)}}</div>
                    </div>
                </template>
                <sc-form-table ref="table" v-model="form.from_account" placeholder="暂无数据" :addTemplate="addTemplate" height="250">
                    <el-table-column label="金额" align="center" prop="amount">
                        <template #default="scope">
                            <el-input v-model="scope.row.amount" placeholder="请输入汇款金额" clearable type="number" @mousewheel.prevent @input="calcForm" @focus="common.inputFocus($event)"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="账户" align="center" prop="account"></el-table-column>
                    <el-table-column label="备注" align="center" prop="remark">
                        <template #default="scope">
                            <el-input v-model="scope.row.remark" placeholder="请输入备注" clearable></el-input>
                        </template>
                    </el-table-column>
                </sc-form-table>
            </el-form-item>
            <el-form-item label="国内接受账户" prop="to_account">
                <template #label>
                    <div>
                        <div style="font-size: 14px">国内接受账户</div>
                        <div style="font-size: 14px">接受总额: {{common.formatNumber(to_amount, 0)}}</div>
                    </div>
                </template>
                <sc-form-table ref="table" v-model="form.to_account" placeholder="暂无数据" :addTemplate="addTemplate" height="250">
                    <el-table-column label="金额" align="center" prop="amount">
                        <template #default="scope">
                            <el-input v-model="scope.row.amount" placeholder="请输入汇款金额" clearable type="number" @mousewheel.prevent @input="calcTo" @focus="common.inputFocus($event)"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="账户" align="center" prop="account"></el-table-column>
                    <el-table-column label="备注" align="center" prop="remark">
                        <template #default="scope">
                            <el-input v-model="scope.row.remark" placeholder="请输入备注" clearable></el-input>
                        </template>
                    </el-table-column>
                </sc-form-table>
            </el-form-item>
            <el-form-item label="汇款日期" prop="date">
                <el-date-picker v-model="form.date" type="datetime" placeholder="请选择汇款日期" style="width: 100%;" :value-format="'YYYY-MM-DD HH:mm:ss'"></el-date-picker>
            </el-form-item>
        </el-form>
        <template #footer>
			<el-button @click="visible = false">取 消</el-button>
			<el-button v-if="mode != 'show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
		</template>
	</el-dialog>
</template>

<script>

export default {
	emits: ['success', 'closed'],
	data() {
		return {
			mode: "add",
			titleMap: {
				add: '新增回款',
				edit: '编辑回款',
				show: '查看'
			},
			visible: false,
			isSaveing: false,
			//表单数据
			form: {
				id: "",
                exchange_rate: "",
                middleman_id: "",
                date: this.moment().format("YYYY-MM-DD HH:mm:ss"),
                from_account: [],
                to_account: [],
			},
			//验证规则
			rules: {
				name: [{ required: true, message: '请输入名称' }],
			},
            accountList: [],
            middleList: [],
            addTemplate: {},
            total_amount: 0,
            form_amount: 0, //国外扣款合计
            to_amount: 0, //国内接受合计
		}
	},
	mounted() {
        this.getAccount();
        this.getMiddle()
	},
	methods: {
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
		//表单提交方法
		submit() {
            if(Number(this.form_amount) != Number(this.to_amount)) return this.$alert("国外扣款合计和国内接受合计不相等,请检查!", "提示", { type: 'error' })
			this.$refs.dialogForm.validate(async (valid) => {
				if (valid) {
					this.isSaveing = true;
					var res = [];
					if (this.form.id) {
						res = await this.$API.business.finance.return.edit.post(this.form);
					} else {
						res = await this.$API.business.finance.return.add.post(this.form);
					}
					this.isSaveing = false;
					if (res.code == 1) {
						this.$emit('success', this.form, this.mode)
						this.visible = false;
						this.$message.success("操作成功")
					} else {
						this.$alert(res.message, "提示", { type: 'error' })
					}
				} else {
					return false;
				}
			})
		},
		//表单注入数据
		async setData(data) {
			this.form.id = data.id
            var res = await this.$API.business.finance.return.detail.get({id: data.id})
            this.form.date = res.data.date
            this.form.exchange_rate = res.data.exchange_rate
            this.form.middleman_id = res.data.middleman_id
            let a = []
            res.data.from_account.forEach((item) => {
                a.push({
                    amount: item.amount,
                    account: item.account,
                    account_id: Number(item.account_id),
                    remark: item.remark
                })
            })
            this.form.from_account = a
            let b = []
            res.data.to_account.forEach((item) => {
                b.push({
                    amount: item.amount,
                    account: item.account,
                    account_bank: item.account_bank,
                    remark: item.remark
                })
            })
            this.form.to_account = b
            this.calcForm()
            this.calcTo()
		},
        // 账号
        async getAccount() {
            var res = await this.$API.basic.account.all.get();
            this.accountList = res.data
        },
        // 中间商
        async getMiddle() {
            var res = await this.$API.basic.middle.all.get();
            this.middleList = res.data
        },
        calcForm(){
            let total = 0
            this.form.from_account.forEach((item) => {
                if(item.amount){
                    total = Number(item.amount) + Number(total)
                }
            })
            this.total_amount = (total).toFixed(2)
            if(this.form.exchange_rate){
                this.form_amount = (Number(total) / Number(this.form.exchange_rate)).toFixed(2)
            }
        },
        calcTotal(e){
            this.form_amount = (Number(this.total_amount) / Number(e)).toFixed(2)
        },
        calcTo(){
            let total = 0
            this.form.to_account.forEach((item) => {
                if(item.amount){
                    total = Number(item.amount) + Number(total)
                }
            })
            this.to_amount = (total).toFixed(2)
        },
        accountChange(row){
            let act = this.accountList.find(item => item.id == row.account_id)
            row.account = act.account
            row.account_bank = act.account_bank
        },
        accountformChange(row){
            let act = this.accountList.find(item => item.id == row.account_id)
            row.account = act.account
        },
	}
}
</script>

<style scoped>
.el-card {
	height: 720px;
	overflow-y: scroll;
}
</style>
